<script setup>
import {computed, markRaw, nextTick, onMounted, ref, watch} from "vue";
import Avatar from "@/components/Avatar.vue";
import CommentList from "@/views/Article/CommentList.vue"
import ImageViewer from "@/components/ImageViewer.vue";
import {useRoute} from "vue-router";
import {useBoardStore, useUserStore} from "@/stores/index.js";
import {articleAPI, userAPI} from "@/apis/index.js";
import {ElMessage, ElMessageBox} from "element-plus";

const route = useRoute();
const userStore = useUserStore()
const boardStore = useBoardStore()

const loading = ref(false);
const dailyTopPostLoading = ref(false)
const dailyTopUserLoading = ref(false)
const haveLike = ref(false)
const articleInfo = ref({})
const userInfo = computed(() => userStore.userInfo || {})

const articleId = computed(() => parseInt(route.params.articleId))

const recommendPostList = ref([])
const recommendUserList = ref([])

// 获取每日点赞前5文章
const fetchDailyTopPost = async () => {
  dailyTopPostLoading.value = true
  try {
    const response = await articleAPI.getDailyTopPost()
    if (response.status === 'success') {
      recommendPostList.value = response.data.list
    }
  } catch (error) {
    console.log(error)
  } finally {
    dailyTopPostLoading.value = false
  }
}

// 获取每天点赞前5的用户
const fetchDailyTopUser = async () => {
  dailyTopUserLoading.value = true
  try {
    const response = await userAPI.getDailyTopUser()
    if (response.status === 'success') {
      recommendUserList.value = response.data.list
    }
  } catch (error) {
    console.log(error)
  } finally {
    dailyTopUserLoading.value = false
  }
}

// 获取文章详情
const fetchArticleDetail = async () => {
  loading.value = true
  const data = {
    articleId: articleId.value
  }
  try {
    const response = await articleAPI.getArticleDetail(data)
    if (response.status === 'success') {
      articleInfo.value = response.data
      haveLike.value = response.data.haveLike
      boardStore.setActiveBoard(articleInfo.value.pBoardId, articleInfo.value.boardId)
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 当前用户是否点赞
const isLike = haveLike

// 点赞文章
const doLikeHandler = async () => {
  const data = {
    articleId: articleId.value
  }
  try {
    const response = await articleAPI.likeArticle(data)
    if (response.status === 'success') {
      isLike.value = response.data.isLiked
      if (isLike.value) {
        ElMessage.success('Do like successful')
        articleInfo.value.goodCount += 1
      } else {
        ElMessage.success('Unsubscribed like successfully')
        articleInfo.value.goodCount -= 1
      }
    }
  } catch (error) {
    console.log(error)
  }
}

//文章图片预览
const imageViewerRef = ref(null);
const previewImgList = ref([]);
const imagePreview = () => {
  nextTick(() => {
    const detailElement = document.querySelector("#detail");
    if (!detailElement) {
      console.warn("Detail element not found, retrying...");
      // 如果元素不存在，延迟重试
      setTimeout(() => {
        imagePreview();
      }, 100);
      return;
    }

    const imageNodeList = detailElement.querySelectorAll("img");
    const imageList = [];
    imageNodeList.forEach((item, index) => {
      const src = item.getAttribute("src");
      imageList.push(src);
      item.addEventListener("click", () => {
        imageViewerRef.value.show(index);
      });
    });
    previewImgList.value = imageList;
  });
};

// 滚动到某个位置
const goToPostion = (position) => {
  if (position === 'top') {
    // 滚动到页面顶部
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  } else if (position === 'view-comment') {
    // 滚动到评论区域
    const commentElement = document.getElementById('view-comment');
    if (commentElement) {
      commentElement.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      });
    }
  }
}

// 删除文章
const deletePost = async () => {
  const data = {
    articleId: articleId.value
  }
  // 删除提示
  ElMessageBox.confirm(
      'The post will be permanently deleted. Continue?',
      'Warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  ).then(async () => {
    try {
      const response = await articleAPI.deletePost(data)
      if (response.status === 'success') {
        ElMessage.success('Do delete successfully')
      }
    } catch (error) {
      console.log(error)
    }
  })

}

// 加载数据
const loadData = () => {
  fetchArticleDetail()
  fetchDailyTopPost()
  fetchDailyTopUser()
}

onMounted(async () => {
  loadData()
  // 确保文章内容加载完成后再初始化图片预览
  await nextTick(() => {
    imagePreview()
    // 检查是否有 hash，如果有则滚动到对应位置
    if (route.hash === '#view-comment') {
      setTimeout(() => {
        goToPostion('view-comment')
      }, 100)
    }
  })
})

watch(() => route.params.articleId, loadData)
</script>

<template>
  <div class="container-body article-detail-body">
    <!--板块导航-->
    <div class="board-info">
      <router-link to="/" class="a-link">Home Page</router-link>
      <el-icon>
        <ArrowRight/>
      </el-icon>
      <router-link :to="`/board/${articleInfo.pBoardId}`" class="a-link">
        {{ articleInfo.pBoardName }}
      </router-link>
      <el-icon>
        <ArrowRight/>
      </el-icon>
      <template v-if="articleInfo.boardId">
        <router-link
            class="a-link"
            :to="`/board/${articleInfo.pBoardId}/${articleInfo.boardId}`"
        >
          {{ articleInfo.boardName }}
        </router-link>
        <el-icon>
          <ArrowRight/>
        </el-icon>
      </template>
      <span>{{ articleInfo.title }}</span>
    </div>
    <!--文章详情-->
    <div class="detail-container">
      <div class="article-detail">
        <!--标题-->
        <div class="skeleton" v-if="loading">
          <el-skeleton :row="5" animated/>
        </div>
        <div v-else>
          <div class="title">
            <span class="tag" v-if="articleInfo.topType == 1">
              Notice
            </span>
            <span>{{ articleInfo.title }}</span>
          </div>
          <div class="expire" v-if="articleInfo.expireTime">
            {{articleInfo.expireTime}} Expire
          </div>
          <!--用户信息-->
          <div class="user-info">
            <Avatar :src="articleInfo.avatar" :width="50"></Avatar>
            <div class="user-info-detail">
              <router-link
                  class="nick-name a-link"
                  :to="`/user/${articleInfo.userId}`"
              >
                {{ articleInfo.nickName }}
              </router-link>
              <span class="institution" v-if="articleInfo.institution">
                  <el-icon><OfficeBuilding /></el-icon>
                  {{ articleInfo.institution }}
              </span>
              <div class="time-info">
                <span>{{ articleInfo.postTime }}</span>
                <!--              编辑按钮-->
                <template v-if="articleInfo.userId == userInfo.userId">
                  <router-link
                      :to="`/editPost/${articleInfo.articleId}`"
                      class="a-link btn-edit"
                  >
                    <span class="edit">Edit</span>
                  </router-link>
                  <el-divider direction="vertical"></el-divider>
                  <span
                      @click="deletePost"
                      class="a-link btn-delete"
                  >
                  Delete
                </span>
                </template>
              </div>
            </div>
          </div>
          <!--文章详情-->
          <div class="detail" id="detail">
            <div v-if="articleInfo && articleInfo.content" v-html="articleInfo.content.replace(/\n/g, '<br>')"></div>
            <div v-for="img in articleInfo.imageList" class="img-detail">
              <el-image :src="img"></el-image>
            </div>
          </div>
        </div>
      </div>

      <!--评论-->
      <div class="comment-panel" id="view-comment">
        <CommentList
            :articleId="articleId"
            :articleUserId="articleInfo.userId"
            :allowComment="articleInfo.allowComments"
        ></CommentList>
      </div>
      <!--推荐文章-->
      <div class="toc-panel">
        <div class="top-container">
          <div class="skeleton" v-if="dailyTopPostLoading">
            <el-skeleton :row="5" animated/>
          </div>
          <div v-else>
            <div class="toc-title">Daily Hot Posts</div>
            <div class="toc-list">
              <div v-for="(item, index) in recommendPostList" class="toc-item">
                <router-link :to="`/post/${item.articleId}`">
                  <span class="item-number">{{ index + 1 }}</span>
                  <span class="item-title">{{ item.title }}</span>
                </router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--推荐用户-->
      <div class="toc-panel-user">
        <div class="top-container-user">
          <div class="skeleton" v-if="dailyTopUserLoading">
            <el-skeleton :row="5" animated/>
          </div>
          <div v-else>
            <div class="toc-title">Daily Hot User</div>
            <div class="toc-list">
              <div v-for="(item, index) in recommendUserList" class="toc-item">
                <router-link :to="`/user/${item.userId}`">
                  <Avatar class="item-avatar" :src="item.avatar" :width="40"></Avatar>
                  <span class="item-title">{{ item.nickName }}</span>
                </router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--左侧快捷操作-->
      <div
          class="quick-panel"
      >
        <div class="quick-container">
          <!--点赞-->
          <el-badge
              :value="articleInfo.goodCount"
              type="info"
              :hidden="!articleInfo.goodCount > 0"
          >
            <div class="quick-item" @click="doLikeHandler">
              <el-icon :class="[(haveLike || isLike) ? 'have-like' : '']">
                <Star/>
              </el-icon>
            </div>
          </el-badge>
          <!--评论-->
          <el-badge
              :value="articleInfo.commentCount"
              type="info"
              :hidden="!articleInfo.commentCount > 0"
          >
            <div
                class="quick-item"
                @click="goToPostion('view-comment')"
            >
              <el-icon>
                <ChatLineRound/>
              </el-icon>
            </div>
            <!--去顶部-->
          </el-badge>
          <div
              class="quick-item"
              @click="goToPostion('top')"
          >
            <el-icon>
              <ArrowUpBold/>
            </el-icon>
          </div>
        </div>
      </div>
    </div>

    <ImageViewer ref="imageViewerRef" :imageList="previewImgList"></ImageViewer>
  </div>
</template>

<style scoped lang="scss">
.article-detail-body {
  position: relative;
  width: 1300px;

  .board-info {
    color: #9ba7b9;
    line-height: 35px;

    .icon-right {
      padding: 0px 5px;
    }
  }

  .detail-container {
    width: 1000px;

    .article-detail {
      background: #fff;
      padding: 15px;

      .title {
        font-size: 24px;
        font-weight: 600;

        .tag {
          color: #F56C6C;
          border: 1px solid #F56C6C;
          font-size: 18px;
          border-radius: 3px;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          margin-right: 10px;
        }
      }

      .expire {
        color: #4e5969;
      }

      .user-info {
        margin-top: 15px;
        display: flex;
        padding-bottom: 10px;
        border-bottom: 1px solid #ddd;

        .user-info-detail {
          margin-left: 10px;

          .nick-name {
            text-decoration: none;
            color: #4e5969;
            font-size: 15px;
            margin-right: 10px;
          }

          .institution {
            background-color: var(--el-color-primary);
            color: #fff;
            font-size: 12px;
            border-radius: 3px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 2px 5px;
          }

          .nick-name:hover {
            color: var(--link);
          }

          .time-info {
            margin-top: 5px;
            font-size: 13px;
            color: var(--text2);

            .btn-edit {
              margin-left: 10px;
              font-size: 14px;
            }
          }
        }
      }

      .detail {
        letter-spacing: 1px;
        margin-top: 10px;

        .img-detail {
          margin-top: 20px;
          display: inline-block;
          margin-right: 10px;
          max-width: 200px;
          cursor: pointer;
        }
      }
    }

    .comment-panel {
      margin-top: 20px;
      background: #fff;
      padding: 20px;
    }

    .toc-panel {
      position: absolute;
      top: 40px;
      right: 0px;
      width: 285px;

      .top-container {
        width: 285px;
        position: fixed;
        background: #fff;

        .skeleton {
          padding: 10px;
        }

        .toc-title {
          border-bottom: 1px solid #ddd;
          padding: 10px;
        }

        .toc-list {
          max-height: calc(100vh - 200px);
          overflow: auto;
          padding: 5px;

          .toc-item {
            cursor: pointer;
            display: flex;
            align-items: center;
            line-height: 35px;
            color: #555666;
            border-radius: 3px;
            padding-left: 5px;
            font-size: 14px;
            min-width: 0;
            max-width: 270px;

            a {
              display: flex;
              align-items: center;
              text-decoration: none;
              color: inherit;
              width: 100%;
              min-width: 0;
            }

            .item-number {
              display: inline-flex;
              align-items: center;
              justify-content: center;
              width: 20px;
              height: 20px;
              background: #409EFF;
              color: white;
              font-size: 12px;
              font-weight: bold;
              margin-right: 8px;
              flex-shrink: 0;
            }

            .item-title {
              flex: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              min-width: 0; // 确保文本能够正确收缩
            }
          }

          .toc-item:first-child .item-number {
            background-color: var(--el-color-danger);
          }

          .toc-item:nth-child(2) .item-number {
            background-color: var(--el-color-warning);
          }

          .toc-item:hover {
            background: #eeeded;
          }

          .active {
            border-left: 2px solid #6ca1f7;
            border-radius: 0px 3px 3px 0px;
            background: #eeeded;
          }
        }
      }
    }

    .toc-panel-user {
      position: absolute;
      top: 280px;
      right: 0px;
      width: 285px;

      .top-container-user {
        width: 285px;
        position: fixed;
        background: #fff;

        .skeleton {
          padding: 10px;
        }

        .toc-title {
          border-bottom: 1px solid #ddd;
          padding: 10px;
        }

        .toc-item {
          cursor: pointer;
          display: flex;
          align-items: center;
          line-height: 50px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          color: #555666;
          border-radius: 3px;
          padding-left: 5px;
          font-size: 14px;

          .item-avatar {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-right: 8px;
            margin-top: 5px;
            margin-bottom: 5px;
          }

          .item-title {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        .toc-item:hover {
          background: #eeeded;
        }
      }
    }

    .quick-panel {
      position: absolute;
      width: 50px;
      left: -80px;
      top: 200px;
      text-align: center;

      .quick-container {
        position: fixed;
        display: flex;
        flex-direction: column;

        .el-badge__content.is-fixed {
          top: 5px;
          right: 15px;
        }

        .quick-item {
          width: 50px;
          height: 50px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 50%;
          background: #fff;
          margin-bottom: 30px;
          cursor: pointer;

          .icon {
            font-size: 22px;
            color: var(--text2);
          }

          .have-like {
            color: red;
          }
        }
      }
    }
  }
}
</style>